<?php
/**
 * Created by PhpStorm.
 * User: UEWARE
 * Date: 2019-7-9
 * Time: 14:50:29
 */

namespace App\Http\Controllers\WeChat;

use App\Http\Controllers\Controller;
use App\Exceptions\Error;
use App\Models\UserModel;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;

class WeChatController extends Controller
{
    /**
     * 是否必须登录
     *
     * @var bool
     */
    protected $requireLogin = true;

    /**
     * 当前登录的用户ID
     *
     * @var null
     */
    protected $userId = null;

    /**
     * 当前登录的用户openId
     *
     * @var null
     */
    protected $openId = null;

    /**
     * sessionKey
     *
     * @var null
     */
    protected $sessionKey = null;

    /**
     * 当前登录的用户信息
     *
     * @var null
     */
    protected $user = null;

    /**
     * BaseController constructor.
     */
    public function __construct(Request $request)
    {
        parent::__construct();

        // 非必须登录，该属性会绕过身份鉴权，请谨慎
        if (!$this->requireLogin) {
            return true;
        }

        $token                = $request->header('Token');

        if (empty($token)) {
            Log::error('ERROR:210003:无效的用户身份 Token 丢失，Token:'.$token);
            throw new Error(210003, '无效的用户身份');
        }

        try {
            $token = Crypt::decrypt($token);
        } catch (\Exception $exception) {
            Log::error('token:' . var_export($token, true));
            Log::error('ERROR:110003:token解密错误');
            throw new Error(110003, 'token解密错误');
        }

        $this->openId     = $token['openid'];
        $this->sessionKey = $token['session_key'];

        Log::debug('token:' . var_export($token, true));

        // 查询用户信息
        try {
            Log::info('open_id:' . $this->openId);
            $user = UserModel::query()->where('openid', $this->openId)->first();

            // 如果用户不存在，先写入，再查询，避免清数据导致的身份失效
            if (empty($user) || !is_object($user)) {
                $user = $this->createUser();
            }

            $user = $user->toArray();
        } catch (\Exception $exception) {
            Log::error('ERROR:110005:用户信息查询失败');
            throw new Error(110005, '用户信息查询失败');
        }

        $this->user         = $user;
        $this->userId       = $user['id'];

        return true;
    }
}